package com.feel.mall.userservice.service;

import com.feel.mall.common.bean.Collect;
import com.feel.mall.common.exception.FeelException;
import com.feel.mall.common.service.CollectService;
import com.feel.mall.common.service.GoodsService;
import com.feel.mall.userservice.mapper.CollectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: 刘永钦
 * @Description:
 */
@Service
public class CollectServiceImpl implements CollectService {
    @Autowired
    private CollectMapper collectMapper;

    @DubboReference
    private GoodsService goodsService;

    @Override
    public Boolean addInfo(Collect collect) throws FeelException {
        if (collectMapper.getByGoodsIdAndUserId(collect.getGoodsId(), collect.getUserId()) != null) {
            throw new FeelException("该商品已经收藏,禁止重复收藏");
        }
        return collectMapper.addInfo(collect) == 1;
    }

    @Override
    public Boolean delInfo(Integer id, Integer userId) throws FeelException {
        Collect collect = collectMapper.getById(id);
        if (collect == null) {
            throw new FeelException("收藏不存在,请重试");
        }
        if (!collect.getUserId().equals(userId)) {
            throw new FeelException("权限错误禁止取消收藏");
        }
        return collectMapper.delInfo(id) == 1;
    }

    @Override
    public Collect getByGoodsIdAndUserId(Integer goodsId, Integer userId) {
        return collectMapper.getByGoodsIdAndUserId(goodsId, userId);
    }

    @Override
    public Object getAllByCondition(Collect condition, Integer pageNum, Integer pageSize) {
        if (pageNum == null) {
            List<Collect> list = collectMapper.getAllByCondition(condition);
            list.forEach(collect -> collect.setGoods(goodsService.selectById(collect.getGoodsId())));
            return list;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Collect> list = collectMapper.getAllByCondition(condition);
        PageInfo<Collect> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
}
